<!-- 客户 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="lawyerName">
              <el-input
                v-model="queryParams.lawyerName"
                placeholder="律师名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <i-ep-search />
                搜索
              </el-button>
              <el-button @click="handleResetQuery">
                <i-ep-refresh />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex-x-between">
              <div>
                <el-button type="success" @click="handleOpenDialog()">
                  <i-ep-plus />
                  新增
                </el-button>
                <el-button
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                >
                  <i-ep-delete />
                  批量删除
                </el-button>
              </div>
            </div>
          </template>

          <el-table
            loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              key="id"
              label="编号"
              align="center"
              prop="id"
              width="80"
            />
            <el-table-column
              key="lawyerName"
              label="律师名称"
              align="center"
              prop="lawyerName"
              width="160"
            />

            <el-table-column
              label="律所"
              align="center"
              width="180"
              prop="lawFirmName"
            />

            <el-table-column
              label="职位名称"
              width="150"
              align="center"
              prop="jobTitle"
            />

            <el-table-column label="手机号码" align="center" width="140">
              <template #default="scope">
                <div v-if="scope.row.isPhone">
                  {{ judgePhone(scope.row.phone.toString()) }}
                  <Hide
                    style="width: 1em; height: 1em; margin-left: 8px"
                    @click="scope.row.isPhone = !scope.row.isPhone"
                  />
                </div>
                <div v-else>
                  {{ scope.row.phone }}
                  <View
                    style="width: 1em; height: 1em; margin-left: 8px"
                    @click="scope.row.isPhone = !scope.row.isPhone"
                  />
                </div>
              </template>
            </el-table-column>

            <el-table-column label="领域" align="center">
              <template #default="scope">
                <div class="categoryInfo-item">
                  <text
                    v-for="item in scope.row.categoryInfoList"
                    :key="item.id"
                    class="text"
                  >
                    {{ item.categoryName }}
                  </text>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleOpenDialog(scope.row.id)"
                >
                  <i-ep-edit />
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.current"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      @close="handleCloseDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="180px"
      >
        <el-form-item label="律师名称" prop="lawyerName">
          <el-input
            v-model="formData.lawyerName"
            placeholder="请输入律师名称"
          />
        </el-form-item>

        <el-form-item label="领域" prop="newCategoryLabel">
          <el-select
            v-model="formData.newCategoryLabel"
            multiple
            placeholder="请选择"
            @change="categoryChange"
          >
            <el-option
              v-for="item in bussinessData"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="执业年长" prop="careerTime">
          <el-input
            v-model="formData.careerTime"
            placeholder="请输入执业年长"
          />
        </el-form-item>

        <el-form-item label="律所名称" prop="lawFirmName">
          <el-select
            v-model="formData.lawFirmName"
            @change="lvwFirmSelectChange"
            value-key="id"
          >
            <el-option
              v-for="item in lawfirmData"
              :key="item.id"
              :label="item.lawFirmName"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="职位名称" prop="newJobTitle">
          <el-select
            v-model="formData.newJobTitle"
            multiple
            placeholder="请选择"
            @change="jobChange"
          >
            <el-option
              v-for="item in jobData"
              :key="item.id"
              :label="item.jobName"
              :value="item.jobName"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属城市名称" prop="belongCityNo">
          <el-cascader
            v-model="formData.belongCityNo"
            :options="cityData"
            style="width: 100%"
            :props="cascaderProps"
            :show-all-levels="false"
            @change="cityCascaderChange"
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="律师证书编号" prop="certificateNo">
          <el-input
            v-model="formData.certificateNo"
            placeholder="请输入律师证书编号"
          />
        </el-form-item>

        <el-form-item label="律师头像" prop="newAvatarUrl">
          <img-upload
            v-if="formData.isUpload"
            :list="formData.newAvatarUrl"
            @update-uploaded="updateUpload"
          />
        </el-form-item>

        <el-form-item label="推荐等级" prop="lawyerLevel">
          <el-input
            v-model="formData.lawyerLevel"
            placeholder="请输入推荐等级"
          />
        </el-form-item>

        <el-form-item label="评分" prop="lawyerScore">
          <el-input v-model="formData.lawyerScore" placeholder="请输入评分" />
        </el-form-item>

        <el-form-item label="是否律所管理员" prop="lawFirmAdmin">
          <el-radio-group v-model="formData.lawFirmAdmin">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="平台是否认证" prop="certificationMark">
          <el-radio-group v-model="formData.certificationMark">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" />
        </el-form-item>

        <el-form-item label="服务客户数量" prop="workForNum">
          <el-input
            v-model="formData.workForNum"
            placeholder="请输入服务客户数量"
          />
        </el-form-item>

        <el-form-item label="证书图片" prop="certificateImg">
          <el-input
            v-model="formData.certificateImg"
            placeholder="请输入证书图片"
          />
        </el-form-item>

        <el-form-item label="咨询费用线下-单次" prop="reservationAmount">
          <el-input
            v-model="formData.reservationAmount"
            placeholder="请输入咨询费用线下-单次"
          />
        </el-form-item>

        <el-form-item
          label="咨询人数上限-单时段-线下"
          prop="reservationPersonLimit"
        >
          <el-input
            v-model="formData.reservationPersonLimit"
            placeholder="请输入咨询人数上限-单时段-线下"
          />
        </el-form-item>

        <el-form-item label="电话咨询费用" prop="phoneReservationAmount">
          <el-input
            v-model="formData.phoneReservationAmount"
            placeholder="请输入电话咨询费用"
          />
        </el-form-item>

        <el-form-item label="在线咨询费用-单次" prop="onlineReservationAmount">
          <el-input
            v-model="formData.onlineReservationAmount"
            placeholder="请输入在线咨询费用-单次"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Customers",
  inheritAttrs: false,
});
import lawyerAPI, {
  LawyerPageQuery,
  LawyerForm,
  LawyerPageVO,
} from "@/api/lawyer";
import lawfirmAPI, { LawFirmVO } from "@/api/lawfirm";
import cityAPI from "@/api/city";
import bussinessAPI, { BussinessVO } from "@/api/business";
import jobAPI, { JobVO } from "@/api/job";
import { judgePhone } from "@/utils/helper";

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref<LawyerPageVO[]>();
/** 律所列表 */
const lawfirmData = ref<LawFirmVO[]>();
/** 城市列表 */
const cityData = ref<any>([]);
/** 业务列表 */
const bussinessData = ref<BussinessVO[]>();
/** 职位列表 */
const jobData = ref<JobVO[]>();
const cascaderProps = {
  label: "name",
  value: "id",
  children: "children",
  emitPath: false,
};
/** 用户查询参数  */
const queryParams = reactive<LawyerPageQuery>({
  cityNo: "",
  lawFirmId: undefined,
  lawyerName: "",
  current: 1,
  pageSize: 10,
});

/**  用户弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

// 用户表单数据
const formData = reactive<LawyerForm>({
  isUpload: false,
  id: undefined,
  lawyerNo: "",
  lawyerName: "",
  lawFirmId: undefined,
  lawFirmName: "",
  phone: "",
  jobTitle: "",
  newJobTitle: [],
  jobId: undefined,
  categoryLabel: "",
  newCategoryLabel: "",
  lawyerLevel: undefined,
  lawyerScore: undefined,
  careerTime: "",
  lawFirmAdmin: undefined,
  certificationMark: undefined,
  belongCityNo: undefined,
  belongCityName: "",
  workForNum: undefined,
  certificateImg: "",
  reservationAmount: undefined,
  reservationPersonLimit: "",
  avatarUrl: "",
  newAvatarUrl: [],
  phoneReservationAmount: undefined,
  address: "",
  onlineReservationAmount: undefined,
  certificateNo: "",
});

/** 用户表单校验规则  */
const rules = reactive({
  // lawFirmAdmin: [
  //   { required: true, message: "是否律所管理员不能为空", trigger: "blur" },
  // ],
  lawyerName: [{ required: true, message: "律师不能为空", trigger: "blur" }],
  careerTime: [
    { required: true, message: "执业年长不能为空", trigger: "blur" },
  ],
  jobTitle: [{ required: true, message: "职位不能为空", trigger: "blur" }],
  belongCityNo: [{ required: true, message: "地址不能为空", trigger: "blur" }],
  newAvatarUrl: [{ required: true, message: "头像不能为空", trigger: "blur" }],
  certificateNo: [
    { required: true, message: "律师编号不能为空", trigger: "blur" },
  ],
  newCategoryLabel: [
    { required: true, message: "领域不能为空", trigger: "blur" },
  ],
  lawFirmName: [{ required: true, message: "律所不能为空", trigger: "blur" }],
  phone: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  lawyerAPI
    .getLawyer(queryParams)
    .then((data) => {
      console.log(data, "律师列表");
      let newList = data.records.map((item: any) => ({
        ...item,
        isPhone: true,
      }));
      pageData.value = newList;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  lawfirmData.value = await lawfirmAPI.getLawfirmAll();
  cityData.value = await cityAPI.getCity();
  bussinessData.value = await bussinessAPI.getBussiness();
  jobData.value = await jobAPI.getJob();
  if (id) {
    dialog.title = "修改用户";
    lawyerAPI.getLawyerById(id).then((data) => {
      // console.log(data, "根据ID查数据");
      Object.assign(formData, {
        ...data,
        belongCityNo: Number(data.belongCityNo),
      });
      let categoryList = data.categoryInfoList.map((item: any) => item.id);
      formData.newCategoryLabel = [...categoryList];
      formData.newJobTitle = data.jobTitle?.split(",");
      if (data.avatarUrl != "" && formData.newAvatarUrl) {
        formData.newAvatarUrl.push(data.avatarUrl);
      }
      formData.isUpload = true;
    });
  } else {
    formData.isUpload = true;
    dialog.title = "新增用户";
  }
}
/** 选中律所时触发 */
const lvwFirmSelectChange = (item: any) => {
  formData.lawFirmId = item.id;
  formData.lawFirmName = item.lawFirmName;
};
/** 城市选择时触发 */
const cityCascaderChange = (item: any) => {
  // console.log(item, formData, "城市选择");
  let address = findById(cityData.value, item);
  formData.belongCityName = address.name;
};
/** 业务分类选泽时触发 */
const categoryChange = (val: any) => {
  formData.categoryLabel = val.join(",");
  // console.log(val, formData, "业务选择");
};
/** 职位选择时触发 */
const jobChange = (val: any) => {
  formData.jobTitle = val.join(",");
  // console.log(val, formData, "职位选择");
};
/** 上传图片返回函数 */
const updateUpload = (item: string[]) => {
  formData.newAvatarUrl = item;
  if (item.length >= 1) {
    formData.avatarUrl = item[0];
  } else {
    formData.avatarUrl = "";
  }
};
/** 遍历找到对应的城市数据 */
function findById(arr: any, id: number) {
  // console.log(arr, id, "arr");
  // 遍历数组中的每个元素
  for (let i = 0; i < arr.length; i++) {
    // 检查当前元素的id是否匹配
    if (arr[i].id === id) {
      // 如果匹配，返回当前元素
      return arr[i];
    }
    // 如果当前元素有children数组，递归查找
    if (arr[i].children && arr[i].children.length > 0) {
      const result: any = findById(arr[i].children, id);
      if (result) {
        // 如果在children中找到了匹配项，返回它
        return result;
      }
    }
  }
  // 如果没有找到匹配项，返回null或undefined（这里返回null表示明确没有找到）
  return null;
}
/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
  formData.isUpload = false;
  formData.newCategoryLabel = undefined;
  formData.newJobTitle = undefined;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      lawyerAPI
        .updateLawyer(formData)
        .then(() => {
          if (userId) {
            ElMessage.success("修改用户成功");
          } else {
            ElMessage.success("新增用户成功");
          }
          handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      lawyerAPI
        .deleteLawyerBatch(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss" scoped>
.categoryInfo-item .text::after {
  content: "、";
}
.categoryInfo-item .text:nth-last-of-type(1)::after {
  content: "。";
}
</style>
